package com.jzo2o.market.handler;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jzo2o.market.mapper.ActivityMapper;
import com.jzo2o.market.mapper.CouponMapper;
import com.jzo2o.market.model.domain.Activity;
import com.jzo2o.market.model.domain.Coupon;
import com.jzo2o.market.service.IActivityService;
import com.jzo2o.market.service.ICouponService;
import com.jzo2o.redis.annotations.Lock;
import com.jzo2o.redis.constants.RedisSyncQueueConstants;
import com.jzo2o.redis.sync.SyncManager;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.List;

import static com.jzo2o.market.constants.RedisConstants.Formatter.*;
import static com.jzo2o.market.constants.RedisConstants.RedisKey.COUPON_SEIZE_SYNC_QUEUE_NAME;
import static com.jzo2o.market.enums.ActivityStatusEnum.*;

@Component
public class XxlJobHandler {

    @Resource
    private SyncManager syncManager;

    @Resource
    private IActivityService activityService;

    @Resource
    private ICouponService couponService;

    @Resource
    private ActivityMapper activityMapper;
    @Resource
    private CouponMapper couponMapper;

    /**
     * 活动状态修改，
     * 1.活动进行中状态修改
     * 2.活动已失效状态修改
     * 1分钟一次
     */
    @XxlJob("updateActivityStatus")
    public void updateActivitySatus() {
        LocalDateTime now = LocalDateTime.now();
        List<Activity> activityList = activityMapper.selectList(new QueryWrapper<Activity>().lambda()
                .eq(Activity::getStatus, NO_DISTRIBUTE.getStatus())
                .ge(Activity::getDistributeEndTime, now)
                .le(Activity::getDistributeStartTime, now));
        for (Activity activity : activityList) {
            activity.setStatus(DISTRIBUTING.getStatus());
            activityMapper.updateById(activity);
        }

        List<Activity> activityList1 = activityMapper.selectList(new QueryWrapper<Activity>().lambda()
                .eq(Activity::getStatus, DISTRIBUTING.getStatus())
                .le(Activity::getDistributeEndTime, now));
        for (Activity activity : activityList1) {
            activity.setStatus(LOSE_EFFICACY.getStatus());
            activityMapper.updateById(activity);
        }
    }

    /**
     * 已领取优惠券自动过期任务
     * 用户领取的优惠券如果到达有效期仍然没有使用自动改为“已失效”
     */
    @XxlJob("processExpireCoupon")
    public void processExpireCoupon() {
        LocalDateTime now = LocalDateTime.now();
        List<Coupon> couponList = couponMapper.selectList(new QueryWrapper<Coupon>().lambda()
                .eq(Coupon::getStatus, 1)
                .le(Coupon::getValidityTime, now));
        for (Coupon coupon : couponList){
            coupon.setStatus(3);
            couponMapper.updateById(coupon);
        }
    }


}
